package sun.curriculumschedule;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.teachtown_my1214.R;
import com.xingyuan.unitClassTeaching.GroupPracticeAfterClass;
import com.xingyuan.utils.DatabaseUtil;

import net.tsz.afinal.FinalDb;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by JohnSun on 2016/1/27.
 */
public class LessonScheduleActivity extends Activity implements View.OnClickListener{
    private GridView scheduleGridView;

   // private enum ScheduleMode {EXERXISE,ADD}
    private static final String TAG="LessonScheduleActivity";
    public static String SCHEDULE_TYPE_DATE="date";
    public static String SCHEDULE_TYPE_SECTION="section";
    public static String SCHEDULE_TYPE_MAJOR="major";


    private int [] dateShowId =new int[]{R.id.date1, R.id.date2, R.id.date3, R.id.date4, R.id.date5};
    private TextView monday,tuesday,wednesday,thursday,friday;
    private  int totalNumOfDay;
    private TextView[] dateText=new TextView[]{monday,tuesday,wednesday,thursday,friday};
    private Map<Integer,String> dateMap;
    private FinalDb db;
   private int colors[] = {
           Color.rgb(0xee, 0xff, 0xff),
           Color.rgb(0xf0,0x96,0x09),
           Color.rgb(0x8c,0xbf,0x26),
           Color.rgb(0x00,0xab,0xa9),
           Color.rgb(0x99,0x6c,0x33),
           Color.rgb(0x3b,0x92,0xbc),
           Color.rgb(0xd5,0x4d,0x34),
           Color.rgb(0xcc, 0xcc, 0xcc)
   };

    private LessonScheduleAdapetr scheduleAdapetr;
    private ArrayList<ShowCurriculum> curriculumList;

    public LessonScheduleActivity() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout._my_schedule);
        //初始化控件
        initUiData();

//        dateText[0].setText(dateMap.get(CalendarUtil.Monday));
//        dateText[1].setText(dateMap.get(CalendarUtil.Tuesday));
//        dateText[2].setText(dateMap.get(CalendarUtil.Wednesday));
//        dateText[3].setText(dateMap.get(CalendarUtil.Thursday));
//        dateText[4].setText(dateMap.get(CalendarUtil.Friday));

//        Calendar today=Calendar.getInstance();
//        today.get(Calendar.M);

        //从数据库获取课程信息，并且显示
        DatabaseUtil.createDatabase(this);
         db=DatabaseUtil.getDb();
          showLesson();
      

        scheduleGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //添加课程的名字
                ShowCurriculum getCurricum=curriculumList.get(position);
               if (getCurricum.getMajor().equals("")){

                   //设置majorName 和 singleOrgroup
                   newOneLesson(curriculumList.get(position));
                   int random=(int)(Math.random()*8);
                   view.findViewById(R.id.schedule_name).setVisibility(View.VISIBLE);
                   view.findViewById(R.id.schedule_name).setBackgroundColor(colors[random]);


                   //position 从0 开始
                   SectionUtil section= SectionUtil.getSectionDetail(position);

                   //保存课程信息
                   getCurricum.setDate(dateMap.get(section.getWhichDayOfWeek()-1));
                   getCurricum.setSection(section.getSectionOfDay());
                   getCurricum.setTeacherId(0);

               }
                //进入到 课堂练习，教学，课堂练习，课后练习 页面，传过去
               else{
                   Toast.makeText(LessonScheduleActivity.this,"努力开发中...", Toast.LENGTH_SHORT).show();
                   Toast.makeText(LessonScheduleActivity.this,"进入到课堂练习", Toast.LENGTH_SHORT).show();
                   //存到数据库

                     Intent intent =new Intent(LessonScheduleActivity.this, GroupPracticeAfterClass.class);
                     intent.putExtra(LessonScheduleActivity.SCHEDULE_TYPE_DATE,getCurricum.getDate());
                     intent.putExtra(LessonScheduleActivity.SCHEDULE_TYPE_SECTION,getCurricum.getSection());
                     intent.putExtra(LessonScheduleActivity.SCHEDULE_TYPE_MAJOR,getCurricum.getMajor());
                   startActivity(intent);


               }




            }
        });

     //长按事件
        scheduleGridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                //删除一节课程
              AlertDialog.Builder builder= new AlertDialog.Builder(LessonScheduleActivity.this);
                builder.setTitle("是否删除当前课程");
                builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ShowCurriculum deleteCurri = curriculumList.get(position);
                        db.deleteByWhere(ShowCurriculum.class, "date=" + "'" + deleteCurri.getDate() + "'" + "and section=" + deleteCurri.getSection());
                        deleteCurri.setMajor("");
                        scheduleAdapetr.notifyDataSetChanged();

                    }
                });
                builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                  builder.create().show();


                return true;
            }
        });





    }

    private void initUiData() {
        //日期
        for (int i=0;i<5;i++){
            dateText[i]=(TextView)findViewById(dateShowId[i]);
            dateText[i].setOnClickListener(this);}

        //周改变
        findViewById(R.id.next_week).setOnClickListener(this);
        findViewById(R.id.last_week).setOnClickListener(this);
        curriculumList=new ArrayList<>();
        curriculumList=getSchedule();
        totalNumOfDay=dateText.length;

        //gridView 的点击事件
        scheduleGridView =(GridView)findViewById(R.id.schedule_gridView);
        scheduleAdapetr =new LessonScheduleAdapetr(this,curriculumList);
        scheduleGridView.setAdapter(scheduleAdapetr);

        //初始化
       dateMap = CalendarUtil.getCurrentWeek();
//        for (int i=0;i<totalNumOfDay;i++){
//            dateText[i].setText(dateMap.get(i+1));
//        }
          //当前周日期显示
        getShowTextViewDateData(dateMap);
    }

    private String translateDigitalDateToChinese(String givenDate) {
        String[] tempArray = givenDate.split("-");
        int intMonth = Integer.parseInt(tempArray[1]);
        String ret = intMonth + "月" + tempArray[2] + "日";
        return ret;
    }
    /**
     * 得到TextView现实的日期
     * @param dateMap
     */
    public void getShowTextViewDateData(Map<Integer,String> dateMap){

        for (int i=0;i<totalNumOfDay;i++){
            String temp = translateDigitalDateToChinese(dateMap.get(i));
            dateText[i].setText(temp);
        }

    }


    public void showLesson() {
//        //需要查找当前星期的课程
//        String mon=  dateMap.get(CalendarUtil.Monday);
//        String tu=   dateMap.get(CalendarUtil.Tuesday);
//        String wed=  dateMap.get(CalendarUtil.Wednesday);
//        String thur= dateMap.get(CalendarUtil.Thursday);
//        String fri=  dateMap.get(CalendarUtil.Friday);
//
//        Map<Integer,ArrayList<ShowCurriculum>> showCurMap=new HashMap<>();
//         //对应日期
//          for (int i=1;i<=5;i++){
//              ArrayList<ShowCurriculum> showDay= new ArrayList<>();
//              showCurMap.put(i, showDay);//
//          }
//        ArrayList<ShowCurriculum> all= (ArrayList<ShowCurriculum>) db.findAll(ShowCurriculum.class);
//
//        for (ShowCurriculum addLesson :all){
//            //数据库中的日期
//          String date=addLesson.getDate();
//            if      (date.equals(mon))   {  showCurMap.get(CalendarUtil.Monday).add(addLesson);}
//            else if  (date.equals(tu))   {  showCurMap.get(CalendarUtil.Tuesday).add(addLesson);}
//            else if (date.equals(wed))   {  showCurMap.get(CalendarUtil.Wednesday).add(addLesson);}
//            else if (date.equals(thur))  {  showCurMap.get(CalendarUtil.Thursday).add(addLesson);}
//            else if (date.equals(fri))   {  showCurMap.get(CalendarUtil.Friday).add(addLesson);}
//            else{}
//        }

         Map<Integer,ArrayList<ShowCurriculum>> showCurMap=new HashMap<>();
         //对应日期
          for (int i=1;i<=5;i++){
              ArrayList<ShowCurriculum> showDay= new ArrayList<>();
              showCurMap.put(i, showDay);//
          }
        ArrayList<ShowCurriculum> allShowCurriculum= (ArrayList<ShowCurriculum>) db.findAll(ShowCurriculum.class);
        for (ShowCurriculum oneLesson :allShowCurriculum) {
            //数据库中的日期
            String tempDate = oneLesson.getDate();
            for (int i=0; i<5; i++) {
                if (tempDate.equals(dateMap.get(i))) {
                    showCurMap.get(i+1).add(oneLesson);
                }
            }
        }

        // j对应周一到周五
        for (int j=1;j<=5;j++){
            ArrayList<ShowCurriculum> showDay=showCurMap.get(j);
            for (ShowCurriculum temCurriculum: showDay){
                int secion=temCurriculum.getSection();
                //根据section返回一个Id用来设置curriculumList中显示的内容
                int position= SectionUtil.getPosition(j,secion);
                ShowCurriculum show= curriculumList.get(position);
                show.setSection(secion);
                show.setMajor(temCurriculum.getMajor());
                show.setTeacherId(temCurriculum.getTeacherId());
                show.setDate(temCurriculum.getDate());
            }

        }
    }


    public ArrayList<ShowCurriculum> getSchedule() {
        ArrayList<ShowCurriculum> cuList=new ArrayList<>();
        for (int i=0;i<40;i++){
            ShowCurriculum curriculumSchedule=new ShowCurriculum();
            curriculumSchedule.setMajor("");
            cuList.add(curriculumSchedule);
        }
        return cuList;
    }

    public  void newOneLesson(final ShowCurriculum curriculum) {


        final AlertDialog myDialog = new AlertDialog.Builder(this).create();
        myDialog.show();
        final Window window = myDialog.getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);//设置可以点击，
         window.setContentView(R.layout.new_one_lesson_schedule);
        final EditText nameEditText=(EditText)window.findViewById(R.id.period_name);


        window.findViewById(R.id.confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击确定时添加的方法
                String name = nameEditText.getText().toString().trim();
                curriculum.setMajor(name);

                scheduleAdapetr.notifyDataSetChanged();
                //点击确定后再进行保存，否则保存的数据不是最新的
                DatabaseUtil.getDb().save(curriculum);
                myDialog.dismiss();

            }
        });

        window.findViewById(R.id.cancel)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        myDialog.dismiss();
                    }
                });

        window.findViewById(R.id.single_teaching).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                window.findViewById(R.id.single_teaching).setBackgroundResource(R.drawable.sing_teach_button_light);
                window.findViewById(R.id.group_teaching).setBackgroundResource(R.drawable.group_teaching_button);
                curriculum.setSingleOrGroup(ShowCurriculum.SINGLE);

            }
        });
        window.findViewById(R.id.group_teaching).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                window.findViewById(R.id.group_teaching).setBackgroundResource(R.drawable.group_teaching_button_light);
                window.findViewById(R.id.single_teaching).setBackgroundResource(R.drawable.sing_teaching_button);

                curriculum.setSingleOrGroup(ShowCurriculum.GROUP);

            }
        });
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.next_week:
                //下周显示的日期
                dateMap =CalendarUtil.getNextMonday();
                getShowTextViewDateData(dateMap);

//                dateText[0].setText( dateMap.get(CalendarUtil.Monday));
//                dateText[1].setText( dateMap.get(CalendarUtil.Tuesday));
//                dateText[2].setText( dateMap.get(CalendarUtil.Wednesday));
//                dateText[3].setText(dateMap.get(CalendarUtil.Thursday));
//                dateText[4].setText(dateMap.get(CalendarUtil.Friday));

                changeWeek();

                break;
            case R.id.last_week:

                //得到上周日期
                dateMap =CalendarUtil.getPreviousWeekday();
                getShowTextViewDateData(dateMap);

//                dateText[0].setText(dateMap.get(CalendarUtil.Monday));
//                dateText[1].setText(dateMap.get(CalendarUtil.Tuesday));
//                dateText[2].setText(dateMap.get(CalendarUtil.Wednesday));
//                dateText[3].setText(dateMap.get(CalendarUtil.Thursday));
//                dateText[4].setText(dateMap.get(CalendarUtil.Friday));
                changeWeek();
                break;
        }
    }

    /**
     * 改变周内容，进行的操作
     */
    public void changeWeek() {
        curriculumList.clear();
        curriculumList=getSchedule();
        showLesson();
        scheduleAdapetr.setCurriculumList(curriculumList);
        scheduleAdapetr.notifyDataSetChanged();
    }

    public void setNeedDate(String date){


    }

}